import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { MessageIndexDto } from './message.dto';
import { MessageModel } from './message.model';
import { UserModel } from '@/module/user/user.model';
import { BooleanNumber, Direction, MessageContentType } from "common/utils/data";

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(MessageModel)
    private readonly messageModelRepository: Repository<MessageModel>,
  ) {}

  async indexMine(
    query: MessageIndexDto,
    user: UserModel,
  ) {
    const queryBuilder = this.messageModelRepository.createQueryBuilder('message')
      .select(
        [
          'message.id',
          'message.uuid',
          'message.content',
          'message.isRead',
          'message.createTime'
        ]
      )
      .where(`(message.userUuid = '${user.uuid}')`)

    query.wrapQueryBuilder(queryBuilder,'message')

    const res = await queryBuilder.getManyAndCount();
    // 因为需要刷新数字，必须同步
    await this.read(res[0]);
    return res;
  }

  async countUnread(user: UserModel){
    const count = await this.messageModelRepository.count({
      where: {
        userUuid: user.uuid,
        isRead: BooleanNumber.false,
      }
    });
    return {
      count,
    }
  }

  private async read(list: MessageModel[]) {
    const notReadUuids: string[] = [];
    list.forEach((item) => {
      if (!item.isRead) {
        notReadUuids.push(item.uuid);
      }
    });
    if (notReadUuids.length) {
      await this.messageModelRepository.update(
        {
          uuid: In(notReadUuids),
        },
        {
          isRead: 1,
        },
      );
    }
  }

  async create(params: {
    contentType: MessageContentType;
    contentTypeOption: any;
    userUuid: string;
  }): Promise<void> {
    const {contentType,contentTypeOption,userUuid} = params;
    const content = this.getTemplate(contentType,contentTypeOption);
    await this.messageModelRepository.save({
      content,
      userUuid,
    });
  }

  private getTemplate(type: MessageContentType,option:any){
    switch (type) {
      case MessageContentType.ARTICLE_BE_PUBLISH:
        return `您的文章 《${option.articleTitle}》 审核通过，已发布`;
      case MessageContentType.ARTICLE_BE_REVIEW:
        return `您的文章 《${option.articleTitle}》 被管理员置为待审核状态，已下架`;
      case MessageContentType.ARTICLE_BE_REVIEW_BY_SYSTEM:
        return `您的文章 《${option.articleTitle}》 被自动置为待审核状态，已下架`;
      case MessageContentType.ARTICLE_BE_REJECT:
        return `您的文章 《${option.articleTitle}》 审核失败，原因：${option.rejectReason}`;
      case MessageContentType.ARTICLE_BE_STICK:
        return `您的文章 《${option.articleTitle}》 被管理员置顶`;
      case MessageContentType.ARTICLE_BE_UNSTICK:
        return `您的文章 《${option.articleTitle}》 被管理员取消置顶`;
    }
  }
}
